package com.newlink.building.obfuscation

import kotlin.random.Random

/**
 * 混淆调用器
 * 用于随机调用SecurityController中的方法，增加代码复杂度
 */
object Module_Obfuscation_ObfuscationInvoker {

    private val manager = Module_Obfuscation_SecurityController.getInstance()
    private val random = Random(System.currentTimeMillis())

    /**
     * 随机执行一个混淆方法
     * @param seed 种子值，用于影响随机选择
     * @return 返回值始终不变，但会执行混淆逻辑
     */
    @JvmStatic
    fun invokeRandom(seed: Any?): Any {
        val methodIndex = (seed?.hashCode() ?: 0) % 20
        return when (abs(methodIndex)) {
            0 -> manager.processString(seed?.toString(), random.nextInt()) ?: "default"
            1 -> manager.calculateValue(
                random.nextInt(100),
                random.nextInt(100),
                random.nextFloat()
            ) ?: "default"

            2 -> manager.validateData(seed, "key_${System.currentTimeMillis()}") ?: "default"
            3 -> manager.processList(listOf("a", "b", "c"), random.nextInt(10)) ?: "default"
            4 -> manager.transformMap(mapOf("key" to (seed ?: "")), random.nextDouble())
                ?: "default"

            5 -> manager.checkCondition(seed?.toString(), random.nextInt(1000)) ?: "default"
            6 -> manager.encryptData(seed?.toString()?.toByteArray(), "key") ?: "default"
            7 -> manager.complexOperation(random.nextDouble(), random.nextDouble(), 5) ?: "default"
            8 -> manager.obfuscateString(seed?.toString(), "pattern") ?: "default"
            9 -> manager.manipulateArray(intArrayOf(1, 2, 3, 4, 5), random.nextInt(100))
                ?: "default"

            10 -> manager.recursiveProcess(random.nextInt(100), 3) ?: "default"
            11 -> manager.cacheOperation("cache_key", seed, System.currentTimeMillis()) ?: "default"
            12 -> manager.generateHash(seed?.toString(), "salt_${random.nextInt()}") ?: "default"
            13 -> manager.bitwiseOperation(random.nextLong(), random.nextLong(), random.nextInt(4))
                ?: "default"

            14 -> manager.processCollection(listOf(seed ?: ""), random.nextInt()) ?: "default"
            15 -> manager.matrixOperation(3, 3, random.nextDouble()) ?: "default"
            16 -> manager.stateMachine(random.nextInt(5), seed?.toString()) ?: "default"
            17 -> manager.compressData(seed?.toString(), random.nextInt(1, 10)) ?: "default"
            18 -> manager.probabilityCalculation(listOf(0.5, 0.7, 0.9), 0.3) ?: "default"
            19 -> manager.comprehensiveProcess(null, seed, mapOf("option" to "value"), null)
                ?: "default"

            else -> seed ?: "default"
        }
    }

    /**
     * 批量执行混淆方法
     * @param count 执行次数
     * @param data 传入数据
     */
    @JvmStatic
    fun invokeBatch(count: Int, data: Any?) {
        repeat(count) {
            invokeRandom(data)
        }
    }

    /**
     * 链式调用多个混淆方法
     * @param methods 方法索引列表
     * @param initialData 初始数据
     * @return 最终结果
     */
    @JvmStatic
    fun invokeChain(methods: IntArray, initialData: Any?): Any {
        var result: Any = initialData ?: ""
        methods.forEach { methodIndex ->
            result = invokeSpecific(methodIndex, result)
        }
        return result
    }

    /**
     * 调用特定的混淆方法
     * @param methodIndex 方法索引(0-19)
     * @param data 传入数据
     * @return 方法返回值
     */
    @JvmStatic
    fun invokeSpecific(methodIndex: Int, data: Any?): Any {
        return when (methodIndex % 20) {
            0 -> manager.processString(data?.toString(), random.nextInt()) ?: "default"
            1 -> manager.calculateValue(
                data?.hashCode() ?: 1,
                random.nextInt(100),
                random.nextFloat()
            ) ?: "default"

            2 -> manager.validateData(data, "specific_key") ?: "default"
            3 -> manager.processList(
                data?.toString()?.split(",") ?: emptyList(),
                random.nextInt(10)
            ) ?: "default"

            4 -> manager.transformMap(
                mapOf("input" to (data ?: "")),
                random.nextDouble()
            ) ?: "default"

            5 -> manager.checkCondition(data?.toString(), 500) ?: "default"
            6 -> manager.encryptData(
                data?.toString()?.toByteArray(),
                "encryption_key"
            ) ?: "default"

            7 -> manager.complexOperation(
                data?.hashCode()?.toDouble() ?: 1.0,
                2.0,
                3
            ) ?: "default"

            8 -> manager.obfuscateString(data?.toString(), "obfuscate") ?: "default"
            9 -> manager.manipulateArray(
                intArrayOf(data?.hashCode() ?: 0),
                100
            ) ?: "default"

            10 -> manager.recursiveProcess(
                data?.hashCode()?.let { abs(it) % 100 } ?: 10,
                2
            ) ?: "default"

            11 -> manager.cacheOperation(
                "method_${methodIndex}",
                data,
                1000L
            ) ?: "default"

            12 -> manager.generateHash(
                data?.toString(),
                "method_salt"
            ) ?: "default"

            13 -> manager.bitwiseOperation(
                data?.hashCode()?.toLong() ?: 0L,
                12345L,
                methodIndex
            ) ?: "default"

            14 -> manager.processCollection(
                setOf(data ?: ""),
                methodIndex
            ) ?: "default"

            15 -> manager.matrixOperation(2, 2, data?.hashCode()?.toDouble() ?: 1.0) ?: "default"
            16 -> manager.stateMachine(
                methodIndex % 5,
                data?.toString()
            ) ?: "default"

            17 -> manager.compressData(
                data?.toString(),
                max(1, methodIndex % 10)
            ) ?: "default"

            18 -> manager.probabilityCalculation(
                listOf(0.1 * methodIndex),
                0.5
            ) ?: "default"

            19 -> manager.comprehensiveProcess(
                null,
                data,
                mapOf("method" to methodIndex),
                null
            ) ?: "default"

            else -> data ?: "fallback"
        }
    }

    /**
     * 条件执行混淆方法
     * @param condition 执行条件
     * @param trueMethod 条件为真时执行的方法索引
     * @param falseMethod 条件为假时执行的方法索引
     * @param data 传入数据
     */
    @JvmStatic
    fun invokeConditional(
        condition: Boolean,
        trueMethod: Int,
        falseMethod: Int,
        data: Any?
    ): Any {
        val methodToInvoke = if (condition) trueMethod else falseMethod
        return invokeSpecific(methodToInvoke, data)
    }

    /**
     * 异步执行混淆方法
     * @param methodIndex 方法索引
     * @param data 传入数据
     * @param callback 回调函数
     */
    @JvmStatic
    fun invokeAsync(
        methodIndex: Int,
        data: Any?,
        callback: ((Any) -> Unit)?
    ) {
        Thread {
            val result = invokeSpecific(methodIndex, data)
            callback?.invoke(result)
        }.start()
    }

    /**
     * 获取混淆统计信息
     */
    @JvmStatic
    fun getStatistics(): Map<String, Any> {
        return mapOf(
            "counter" to manager.getCounter(),
            "timestamp" to System.currentTimeMillis(),
            "random" to random.nextInt()
        )
    }

    /**
     * 重置混淆状态
     */
    @JvmStatic
    fun reset() {
        manager.reset()
    }

    private fun abs(value: Int): Int {
        return if (value < 0) -value else value
    }

    private fun max(a: Int, b: Int): Int {
        return if (a > b) a else b
    }
}